package com.filter;

import com.alibaba.fastjson.JSON;
import com.bean.JwtOperation;
import com.dto.JsonResult;
import com.dto.User;
import com.entity.UserInfo;
import com.utils.ApplicationContextUtils;
import com.utils.HttpUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.NestedServletException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Yadasu
 * @version 1.0
 * @date 2020/9/29 0029 19:54
 * @usage jwt认证过滤器
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private JwtOperation jwtOperation;
    private UserDetailsService userDetailsService;
    private PasswordEncoder encoder;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        jwtOperation = ApplicationContextUtils.getBean(JwtOperation.class);
        userDetailsService = ApplicationContextUtils.getBean("jdbcUseService", UserDetailsService.class);
        encoder = ApplicationContextUtils.getBean(BCryptPasswordEncoder.class);
        String token = request.getHeader("auth-token");
        JsonResult result = new JsonResult();
        try {
            if (StringUtils.isBlank(token)) {
                throw new BadCredentialsException("没有携带Token信息");
            }
            //解析token
            Claims claims = jwtOperation.parseJwt(token);
            //判断凭证是否不存在
            if (null == claims) {
                throw new BadCredentialsException("无效的凭证信息");
            }
            //从凭证中获取对象信息Json字符串
            Object userClaim = claims.get("user");
            if (null == userClaim) {
                throw new BadCredentialsException("无效的凭证信息");
            }

            //获取用户信息对象
            User user= JSON.parseObject(String.valueOf(userClaim), User.class);
            String username = user.getName();

            //获取jwt明文密码
            String pwd = user.getPassword();
            if (null != username && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //密码不一致，有可能被篡改密码
                if (!StringUtils.equals(userDetails.getPassword(), pwd)) {
                    throw new BadCredentialsException("密码可能被篡改了");
                }
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            chain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BadCredentialsException) {
                result.setCode(401);
                result.setMessage(e.getMessage());
            } else  if (e instanceof NestedServletException){
                result.setCode(401);
                result.setMessage(e.getMessage());
            }else {
                result.setCode(500);
                result.setMessage("服务端异常");
            }
            HttpUtils.writeJson(response, result, result.getCode());
        }
    }
}
